#!/usr/bin/env python
import os, sys
import json
from lisnUtils import *

sys.path.append('../')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dblisn.settings")

from apps.stations.models import Station
from apps.instruments.models import Instrument, InstrumentType
from apps.data.models import Data, DataType, DataDate, DataFile

BD = Utility.MySQL(host = "localhost",
                   user = "lisn",
                   passwd = "lisn",
                   db = "lisn",
                   #verbose=True
                   )

TYPES = {'product':1, 'gps':2, 'magnetometer':3, 'ionosonde':4}

def migrate_itypes():
    for inst in ('product', 'gps', 'magnetometer', 'ionosonde'):
        values = {}
        values['name'] = inst
        values['state'] = 1
        model = InstrumentType(**values)
        model.save()

def migrate_stations():
    rows = BD.select('stations', ['*'], '1')
    for tup in rows:
        values = {}
        values['name'] = tup[1]
        values['country'] = tup[2]
        values['latitude'] = tup[3]
        values['longitude'] = tup[4]
        values['altitude'] = tup[5]
        values['state'] = 1
        if not Station.objects.filter(name=tup[1]):
            model = Station(**values)
            model.save()
    model = Station(id=-1, name='all', country='all', latitude=0, longitude=0, altitude=0, state=0)
    model.save()    

def migrate_instruments():
    rows = BD.select('stations, instruments', ['*'], 'stations.idstation=instruments.idstation')
    for tup in rows:
        sta = Station.objects.get(name=tup[1])
        print sta
        values = {}
        values['station_id'] = sta.pk
        values['type_id'] = TYPES[tup[11]]
        values['lisn_code'] = tup[9]
        values['code'] = tup[10]
        values['network'] = tup[12]
        values['server'] = tup[13]
        values['state'] = tup[14]
        values['last_file'] = tup[15]
        values['last_file_date'] = tup[16]
        if tup[11]=='gps':
            info = json.dumps({'receiver':tup[17], 'antenna':tup[18], 'receiver_number':tup[19], 'antenna_number':tup[20], 'receiver_firmware':tup[21]})
        elif tup[11]=='magnetometer':
            info = json.dumps({'model':tup[17]})
        elif tup[11]=='ionosonde':
            info = json.dumps({'model':'VIPIR', 'TX Antenna':'Log Periodic'})
        values['info'] = info
        model = Instrument(**values)
        model.save()




#migrate_itypes()    
#migrate_stations()
#migrate_instruments()




    
